<!-- 经销商列表 -->
<template>
  <div class="dealer sys-content">
    <page-mod>
      <el-card>
        <div class="query-box">
          <el-form :model="query" inline>
            <el-form-item label="经销商名称:">
              <el-input v-model="query.dealerName" placeholder="请输入经销商名称" clearable/>
            </el-form-item>
            <el-form-item label="经销商编号:">
              <el-input v-model="query.dealerCode" placeholder="请输入经销商编号" clearable/>
            </el-form-item>
            <el-form-item label="启用状态:">
              <el-select v-model="query.enableStatus" placeholder="请选择" clearable>
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
              </el-select>
            </el-form-item>
          </el-form>
          <div class="btns">
            <el-button icon="Search" color="#16b777" @click="load(1)">查询</el-button>
            <el-button icon="Refresh" color="#FF5722" @click="resetSearch">重置</el-button>
          </div>
        </div>
      </el-card>
    </page-mod>
    <page-mod title="经销商数据" icon="Histogram" :showBtn="false" :padBottom="false">
      <el-card v-loading="loading" element-loading-text="拼命加载中">
        <el-table ref="tableRef" :data="dataList" max-height="493" border>
          <el-table-column label="序号" type="index" align="center" width="60"/>
          <el-table-column label="经销商编号" prop="dealerCode" align="center" width="180"></el-table-column>
          <el-table-column label="名称" prop="memberName" align="center"></el-table-column>
          <el-table-column label="手机号" prop="phone" align="center"></el-table-column>
          <el-table-column label="类型" prop="category" align="center">
            <template #default="{row}">
              <span v-if="row.category === '1'">门店经销商</span>
              <span v-if="row.category === '2'">区/县运营中心</span>
              <span v-if="row.category === '3'">市运营中心</span>
              <span v-if="row.category === '4'">省运营中心</span>
            </template>
          </el-table-column>
          <el-table-column label="区域" align="center" show-overflow-tooltip>
            <template #default="{row}">
              <span>{{ row.provinceName + row.cityName + row.regionName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="会员编号" prop="memberCode" align="center" width="180"></el-table-column>
          <el-table-column label="状态" prop="enableStatus" align="center">
            <template #default="{row}">
              <el-tag :type="row.enableStatus ? 'success' : 'danger'">{{ row.enableStatus ? '已启用' : '已禁用' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="绑定产品数量" prop="productNum" align="center"></el-table-column>
          <el-table-column label="创建时间" prop="createdTime" align="center" width="170">
            <template #default="{row}">
              <span>{{ $date(row.createdTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="220">
            <template #default="{row}">
              <el-button type="primary" icon="Edit" link @click="toUpdate(row.dealersId)">修改</el-button>
              <el-divider direction="vertical" />
              <el-button 
                :type="row.enableStatus ? 'danger' : 'success'" 
                :icon="row.enableStatus ? 'WarnTriangleFilled' : 'SuccessFilled'" 
                link 
                @click="doUpdateStatus(row)">
                {{row.enableStatus ? '禁用' : '启用'}}
              </el-button>
              <!-- <el-divider direction="vertical" />
              <el-button type="danger" icon="Delete" link @click="doDelete(row.dealersId)">删除</el-button> -->
              <el-divider direction="vertical" />
              <el-dropdown>
                <el-button type="primary" link>
                  更多<el-icon><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="toViewBindGoods(row.dealersId)">我的产品</el-dropdown-item>
                    <el-dropdown-item>协议下载</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination 
          class="paging"
          v-show="query.total"
          small
          layout="total, sizes, prev, pager, next, jumper" 
          :current-page="query.current" 
          :page-size="query.size"
          :total="query.total"
          @current-change="load"
          @size-change="sizeChange">
        </el-pagination>
      </el-card>
    </page-mod>

    <!-- 新增、编辑弹窗 -->
    <el-dialog v-model="show" title="编辑" top="10vh" width="32.6%" destroy-on-close center draggable @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" size="default" label-position="right" label-width="125px">
        <el-form-item label="经销商类型:" prop="category">
          <el-select v-model="form.category" placeholder="请选择经销商类型">
            <el-option label="门店经销商" value="1" />
            <el-option label="区/县运营中心" value="2" />
            <el-option label="市运营中心" value="3" />
            <el-option label="省运营中心" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="公司名称:" prop="companyName" required>
          <el-input v-model="form.companyName" placeholder="请输入公司名称" clearable/>
        </el-form-item>
        <el-form-item label="区域:" prop="region" required>
          <region-select v-model="form.region" size="large"></region-select>
        </el-form-item>
        <el-form-item label="联系电话:" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" clearable/>
        </el-form-item>
        <el-form-item label="姓名:" prop="dealerName" required>
          <el-input v-model="form.dealerName" placeholder="请输入真实姓名" clearable/>
        </el-form-item>
        <el-form-item label="身份证号码:" prop="idCard" required>
          <el-input v-model="form.idCard" placeholder="请输入身份证号码" clearable/>
        </el-form-item>
        <el-form-item label="身份证附件:" prop="idCardFront" required>
          <upload-img v-model="form.idCardFront" width="400" height="220" uploadIcon="zcytIcon zcyt-shenfenzhengzhengmian" iconSize="100"></upload-img>
        </el-form-item>
        <el-form-item label="" prop="idCardBack" required>
          <upload-img v-model="form.idCardBack" width="400" height="220" uploadIcon="zcytIcon zcyt-shenfenzhengfanmian" iconSize="100"></upload-img>
        </el-form-item>
        <el-form-item label="可绑产品数量:" prop="productNum" required>
          <el-input v-model="form.productNum" type="number" placeholder="请输入可绑产品数量" clearable/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="doUpdate">保存</el-button>
        <el-button size="default" @click="show = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 经销商已绑商品 -->
    <el-dialog v-model="bindShow" title="经销商已绑商品" top="10vh" width="40%" center draggable @close="bindGoods = []">
      <el-table ref="table" :data="bindGoods" max-height="493" border v-loading="loading1" element-loading-text="拼命加载中">
        <el-table-column label="序号" type="index" align="center" width="60"/>
        <el-table-column label="商品图片" prop="memberCode" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column label="商品名称" prop="memberCode" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column label="销售价格" prop="memberCode" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column label="创建时间" prop="memberCode" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" prop="memberCode" align="center" show-overflow-tooltip></el-table-column>
      </el-table>
      <el-pagination 
        class="paging"
        v-show="queryBind.total"
        small
        layout="total, sizes, prev, pager, next, jumper" 
        :current-page="queryBind.current" 
        :page-size="queryBind.size"
        :total="queryBind.total"
        @current-change="loadBindGoods"
        @size-change="bindGoodsSizeChange">
      </el-pagination>
    </el-dialog>
  </div>
</template>

<script setup name="dealer">
  import { getDealerListPagesApi, getDealerInfoApi, updateOrdeleteDealerApi, updateDealerStatusApi } from '@/api/api'
  import { regexPhone, regexIdCard } from '@/utils/utils'
  import { ref, reactive, toRefs, getCurrentInstance, onActivated } from 'vue'

  // 获取注册的全局实列
  const currentThis = getCurrentInstance().appContext.config.globalProperties
  const formRef = ref(null)

  const currentData = reactive({
    loading: false,
    show: false,
    bindShow: false,
    query: {
      dealerName: '',
      dealerCode: '',
      enableStatus: '',
      current: 1,
      size: 20,
      total: 0
    },
    queryBind: {
      current: 1,
      size: 20,
      total: 0
    },
    form: {
      dealersId: '',
      category: '1',
      companyName: '',
      provinceCode: '',
      cityCode: '',
      regionCode: '',
      phone: '',
      dealerName: '',
      idCard: '',
      idCardFront: '',
      idCardBack: '',
      productNum: '',
      region: []
    },
    rules: {
      companyName: [{ required: true, message: '请输入公司名称', trigger: ['blur', 'change'] }],
      dealerName: [{ required: true, message: '请输入真实姓名', trigger: ['blur', 'change'] }],
      idCard: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            if(!value) {
              callback(new Error('请输入身份证号'))
            } else {
              if(!regexIdCard(value)) {
                callback(new Error('请输入正确的身份证号'))
              } else {
                callback()
              }
            }
          } 
        }
      ],
      idCardFront: [{ required: true, message: '请上传身份证正面', trigger: 'blur' }],
      idCardBack: [{ required: true, message: '请上传身份证反面', trigger: 'blur' }],
      productNum: [{ required: true, message: '请输入可绑产品数量', trigger: 'blur' }],
      phone: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            if(!value) {
              callback(new Error('请输入手机号码'))
            } else {
              if(!regexPhone(value)) {
                callback(new Error('手机号码格式不对，且必须是11位'))
              } else {
                callback()
              }
            }
          } 
        }
      ],
      region: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            if(!value.length) {
              callback(new Error('请选择省、市、区县'))
            } else if(value.length === 1) {
              callback(new Error('请选择市、区县'))
            } else if(value.length === 2) {
              callback(new Error('请选择区县'))
            } else if(value.length === 3) {
              callback()
            }
          } 
        }
      ]
    },
    dataList: [],
    bindGoods: []
  })
  let {loading, show, bindShow, query, queryBind, form, rules, dataList, bindGoods} = toRefs(currentData)

  // 查询
  function load(page) {
    currentData.loading = true
    currentData.query.current = page
    getDealerListPagesApi(currentData.query).then(res => {
      currentData.loading = false
      if(res.code === '200') {
        currentData.dataList = res.data.pages
        currentData.query.total = res.data.total
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  function loadBindGoods(page) {

  }

  // 修改前弹窗
  function toUpdate(dealersId) {
    getDealerInfoApi(dealersId).then(res => {
      if(res.code === '200') {
        currentData.form = res.data
        currentData.form.region = [res.data.provinceCode, res.data.cityCode, res.data.regionCode]
        currentData.show  = true
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 执行修改
  function doUpdate() {
    formRef.value.validate((valid) => {
      if (valid) {
        currentThis.$messageBox.confirm('确认修改吗？').then(() => {
          let loading = currentThis.$loading('正在修改，请耐心等待')
          currentData.form.provinceCode = currentData.form.region[0]
          currentData.form.cityCode = currentData.form.region[1]
          currentData.form.regionCode = currentData.form.region[2]
          updateOrdeleteDealerApi('update', currentData.form).then(res => {
            loading.close()
            if(res.code === '200') {
              currentThis.$message.success(res.message)
              currentData.show = false
              load(currentData.query.current)
            } else {
              currentThis.$message.error(res.message)
            }
          })
        }).catch(() => {})
      } else {
        return false;
      }
    })
  }

  // 启用或禁用
  function doUpdateStatus(e) {
    currentThis.$messageBox.confirm(`确认${e.enableStatus ? '禁用' : '启用'}吗？`).then(() => {
      let loading = currentThis.$loading('正在处理，请耐心等待')
      updateDealerStatusApi(e.dealersId, e.enableStatus ? 0 : 1).then(res => {
        loading.close()
        if(res.code === '200') {
          currentThis.$message.success(res.message)
          load(currentData.query.current)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  // 删除
  function doDelete(dealersId) {
    currentThis.$messageBox.confirm('确认删除吗？').then(() => {
      let loading = currentThis.$loading('正在删除，请耐心等待')
      updateOrdeleteDealerApi('delete', { 
        id: dealersId 
      }).then(res => {
        loading.close()
        if(res.code === '200') {
          currentThis.$message.success(res.message)
          load(currentData.query.current)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  function toViewBindGoods(dealersId) {
    currentData.bindShow = true
  }
  
  // 重置查询
  function resetSearch() {
    currentData.query.dealerName = ''
    currentData.query.dealerCode = ''
    currentData.query.enableStatus = ''
    load(1)
  }

  // 新增编辑弹窗重置数据
  function resetForm() {
    currentData.form = {
      dealersId: '',
      category: '1',
      companyName: '',
      provinceCode: '',
      cityCode: '',
      regionCode: '',
      phone: '',
      dealerName: '',
      idCard: '',
      idCardFront: '',
      idCardBack: '',
      productNum: '',
      region: []
    }
    formRef.value.resetFields()
  }

  // 分页每页显示条数改变执行
  function sizeChange(size) {
    currentData.query.size = size
    load(1)
  }
  function bindGoodsSizeChange(size) {
    currentData.queryBind.size = size
    loadBindGoods(1)
  }

  onActivated(() => {
    load(currentData.query.current)
  })
</script>

<style lang="less" scoped>
.dealer{
  :deep(.el-dialog){
    .el-dialog__body{
      max-height: 500px;
      overflow: hidden auto;
      .el-form-item__content{
        >.el-input{
          width: 300px;
        }
      }
      .idCard_upload{
        width: 400px; 
        height: 200px;
        border-radius: 8px;
        border: 1px dashed #DCDFE6;
        cursor: pointer;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        font-size: 100px;
        color: #DCDFE6;
        &:hover{
          border-color: #409EFF;
        }
        span{
          color: #8a8b8b;
        }
      }
    }
  }
}
</style>